package easypal.brilliard.world.brilliards.communication.impl;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import easypal.brilliard.util.TraceUtil;
import easypal.brilliard.world.brilliards.communication.CommunicationChannel;
import easypal.brilliard.world.brilliards.communication.CommunicationException;
import easypal.brilliard.world.brilliards.communication.CommunicationListener;

/*
 * TCP is connection-oriented communication protocol, so he need a listener and a connector.
 */
public class CommunicationListenerSocketImpl implements CommunicationListener {
	protected int port;
	
	protected ServerSocket serverSocket;
	
	public CommunicationListenerSocketImpl(int port) {
		this.port = port;
	}
	
	@Override
	public void init() throws CommunicationException{
		try {
			serverSocket = new ServerSocket(this.port);
		} catch (IOException e) {
			String exceptionMessage = "Communication listener can't establish server socket.";
			throw new CommunicationException(exceptionMessage, e);
		}
		
	}

	@Override
	public CommunicationChannel accept()  throws CommunicationException {
		Socket socket = null;
		try {
			socket = serverSocket.accept();
		} catch (IOException e) {
			String exceptionMessage = "Communication listener can't accept a client socket.";
			throw new CommunicationException(exceptionMessage, e);
		}
		
		return new CommunicationChannelSocketImpl(socket);
	}

	@Override
	public void destroy() {
		try {
			this.serverSocket.close();
		} catch (IOException e) {
			/* Destruction need not regard exceptions. */
			String exceptionMessage = "Communication listener destruction fails.";
			TraceUtil.trace(this, exceptionMessage);
		} finally {
			this.serverSocket = null;
		}
		
	}

}
